<template>
  <van-field
    v-model="company"
    is-link
    readonly
    required
    :rules="[{ required: true }]"
    label="物流公司"
    placeholder="请选择物流公司"
    @click="show = true"
  />
  <van-field
    required
    clearable
    :rules="[{ required: true }]"
    v-model="backCode"
    label="退货单号"
    placeholder="请填写退货单号"
  />
  <van-field
    clearable
    v-model="remark"
    label="备注"
    placeholder="请填写备注信息"
  />
  <van-button type="primary" block @click="OnSubmit">提交</van-button>

  <!-- 选择物流公司弹出层 -->
  <van-popup v-model:show="show" round position="bottom">
    <van-picker
      :model-value="pickerValue"
      :columns="columns"
      @cancel="show = false"
      @confirm="OnConfirm"
    />
  </van-popup>
</template>

<script setup>
// this代理
const { proxy } = getCurrentInstance();
// 用户数据
const business = proxy.$business;
// orderid
const orderid = ref(proxy.$route.query.orderid ?? 0);
// 弹出层显示状态
const show = ref(false);
// 物流公司输入框响应式数据
const company = ref("");
// 物流公司的id
const comid = ref(0);
// 物流公司列表选择数据
const columns = ref([]);
// 选择的响应式数据
const pickerValue = ref([]);
// 退货单号
const backCode = ref("");
// 备注信息
const remark = ref("");

// 挂载前钩子
onBeforeMount(() => {
  // 获取物流公司数据
  GetExpressData();
  // 查询用户是否已经填写，如果已经填写则回退
  CheckBack();
});

// 检查是否填写
const CheckBack = async () => {
  // 组装参数
  const params = {
    busid: business.value.id,
    orderid: orderid.value,
  };
  // 发起请求
  const result = await proxy.$http.post({
    url: "/order/checkBack",
    params,
  });
  // 处理请求结果
  if (result.code === 0) {
    proxy.$fail({
      message: result.msg,
      onClose: () => {
        // 回退到上一页
        proxy.$router.back();
      },
    });
  }
};
// 获取物流公司数据
const GetExpressData = async () => {
  // 直接发起请求
  const result = await proxy.$http.post({
    url: "/order/company",
  });
  // 处理请求结果
  if (result.code === 1) {
    columns.value = result.data.map((item) => ({
      text: item.name,
      value: item.id,
    }));
  } else {
    proxy.$fail(result.msg);
  }
};

// 确认选择
const OnConfirm = ({ selectedOptions }) => {
  // 将选中的值（物流公司名称）赋值给company 物流公司id给comid
  company.value = selectedOptions[0].text;
  comid.value = selectedOptions[0].value;
  // 关闭弹出层
  show.value = false;
};

// 提交
const OnSubmit = async () => {
  // 非空校验
  if (company.value.trim() === "") {
    proxy.$fail("请选择物流公司");
    return;
  }
  if (backCode.value.trim() === "") {
    proxy.$fail("请填写退货物流单号");
    return;
  }
  // 组装参数
  const params = {
    busid: business.value.id,
    expressid: comid.value,
    orderid: orderid.value,
    expresscode: backCode.value,
    remark: remark.value,
  };
  console.log(params);
  // 发起请求
  const result = await proxy.$http.post({
    url: "/order/back",
    params,
  });
  // 处理请求结果
  if (result.code === 1) {
    proxy.$success({
      message: result.msg,
      onClose: () => {
        // 跳转回订单页
        proxy.$router.push({ path: "/order" });
      },
    });
  } else {
    proxy.$fail(result.msg);
  }
};
</script>